import datetime
import logging
import os
from typing import Any

from aiogram import types
from aiogram.types import BufferedInputFile
from aiogram_dialog import ChatEvent, DialogManager
from aiogram_dialog.widgets.kbd import Checkbox
from fluentogram import TranslatorRunner

from src.application.order.enums import OrderType
from src.application.order.service import OrderService
from src.application.user.service import UserService
from src.infrastructure.constants import MEDIA_FOLDER
from src.infrastructure.db.exporters import export_proxies_to_csv
from src.infrastructure.db.services.allowed_ips import get_allowed_ip_by_order
from src.infrastructure.db.services.servers import get_server
from src.infrastructure.utils.files import read_file

logger = logging.getLogger(__name__)


async def export_csv(call: types.CallbackQuery, widget: Any, manager: DialogManager):
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    order_id: int = manager.dialog_data.get("order_id")
    order_service: OrderService = manager.middleware_data.get("order_service")

    order = await order_service.get_order_by_id(order_id)

    if len(order.proxies) > 0:
        server = await get_server(db_session, order.proxies[0].server_id)
        allowed_ip = await get_allowed_ip_by_order(db_session, order.user.tg_id, order_id)

        csv = export_proxies_to_csv(order, order.proxies, server, allowed_ip)

        await call.message.answer_document(
            types.BufferedInputFile(
                csv,
                filename=f"Proxies {datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.csv",
            )
        )
    else:
        await call.answer(locale.get("no-proxies-in-order"))


async def send_qr_code(call: types.CallbackQuery, _, manager: DialogManager):
    order_id: int = manager.dialog_data.get("order_id")
    user_service: UserService = manager.middleware_data.get("user_service")

    user = await user_service.get_user_by_tg_id(call.from_user.id)
    content = read_file(os.path.join(MEDIA_FOLDER, f"{user.tg_id}_{order_id}_vpn_qr.png", "rb"))
    await call.message.answer_photo(BufferedInputFile(content, filename="qr_code.png"))


async def send_vpn_config(call: types.CallbackQuery, _, manager: DialogManager):
    order_id: int = manager.dialog_data.get("order_id")
    user_service: UserService = manager.middleware_data.get("user_service")

    user = await user_service.get_user_by_tg_id(call.from_user.id)
    content = read_file(os.path.join(MEDIA_FOLDER, f"{user.tg_id}_{order_id}_vpn.conf", "rb"))
    await call.message.answer_document(BufferedInputFile(content, filename=f"{call.from_user.id}_{order_id}_vpn.conf"))


async def change_autorenew(event: ChatEvent, checkbox: Checkbox, manager: DialogManager):
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    order_service: OrderService = manager.middleware_data.get("order_service")

    if manager.start_data:
        order_id: int = manager.start_data.get("order_id")
    else:
        order_id: int = manager.dialog_data.get("order_id")

    auto_renew: bool = not checkbox.widget.default

    await order_service.set_order_autorenew(order_id, auto_renew)
    await event.answer(locale.get("order-changed-success"))
    order = await order_service.get_order_by_id(order_id)
    if auto_renew:
        if order.order_type == OrderType.subscription:
            await event.message.answer(locale.get("subscription-autorenew-on-msg"))
        else:
            await event.message.answer(locale.get("autorenew-on-msg"))

    await event.answer(locale.get("error-msg"))
